<template>
  <div class="index">
    <div class="header">
      <div class="logo">
        <span class="iconfont iconnew"></span>
      </div>
      <div class="search" @click="$router.push({ name: 'Search' })">
        <van-icon name="search" />
        <span>搜索商品</span>
      </div>
      <!-- <div
        class="user"
        @click="
          try {
            $router.push({ path: `/personal/${id}` });
          } catch (err) {}
        "
      > -->
      <div class="user" @click="$router.push({ path: `/personal/${id}` })">
        <van-icon name="manager-o" />
      </div>
    </div>
    <van-tabs sticky swipeable v-model="active">
      <!-- 遍历得到的栏目分类 -->
      <van-tab
        v-for="(item, index) in categroyList"
        :key="index"
        :title="item.name"
      >
        <!-- loading,finished 存到categoryList里面-->
        <van-list
          v-model="item.loading"
          :finished="item.finished"
          finished-text="没有更多了"
          @load="onLoad"
          :immediate-check="false"
          :offset="10"
        >
          <!-- 实现下拉刷新  利用组件   里面有一个方法，还有一个参数，参数加入到之前的数据处理中-->
          <van-pull-refresh v-model="item.isLoading" @refresh="onRefresh">
            <!-- 这里我们遍历生成 item 为数组categroyList 这里我们遍历postList -->
            <mypostlist
              v-for="(v, index) in item.postList"
              :key="index"
              :postList="v"
            ></mypostlist>
            <!-- 这里插入滑动跳转分类 -->
          </van-pull-refresh>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { categroyList } from "@/apis/category";
import { getpostlist } from "@/apis/article";
import mypostlist from "@/components/mypostlist"; //列表组件

export default {
  components: { mypostlist },
  data() {
    return {
      categroyList: [],
      id: "-1", //给一个默认值，没有token会返回登陆页
      active: window.localStorage.getItem("toutiao_token") ? 1 : 0,
      // active: JSON.parse(window.localStorage.getItem("toutiao")).data.user.id
      //   ? 1
      //   : 0,
      // loading: false,   不能再data里面使用，因为会影响每一个栏目，只能把这两个数据存到数组中
      // finished: false,
    };
  },
  watch: {
    // 我们可以动态监测active
    active() {
      // console.log(this.active);   每一次变化都能获取到  当postList长度为0，代表没有被加载
      if (this.categroyList[this.active].postList.length == 0) {
        // 运行初始函数
        this.init();
      }
    },
  },
  methods: {
    // 封装init 获取栏目函数
    async init() {
      let result = await getpostlist({
        category: this.categroyList[this.active].id,
        pageIndex: this.categroyList[this.active].pageIndex,
        pageSize: this.categroyList[this.active].pageSize,
      });
      this.categroyList[this.active].postList.push(...result.data.data);
      // console.log(this.categroyList);
      this.categroyList[this.active].loading = false;
      if (result.data.data.length < this.categroyList[this.active].pageSize) {
        this.categroyList[this.active].finished = true;
      }
      // console.log(this.categroyList);
    },
    async onLoad() {
      // console.log(1);
      // 当触发onLoad事件，把参数页面++，再去请求
      this.categroyList[this.active].pageIndex++;
      // setTimeout(
      //   async () => {
      //   let result = await getpostlist({
      //     category: this.categroyList[this.active].id,
      //     pageIndex: this.categroyList[this.active].pageIndex,
      //     pageSize: this.categroyList[this.active].pageSize,
      //   });
      //   this.categroyList[this.active].postList.push(...result.data.data);
      //   // 将上拉加载组件loading重置为false
      //   this.categroyList[this.active].loading = false;
      //   // console.log(this.categroyList);
      //   // 当条数小于5条时候，我们显示没有更多了,也下拉也不会触发加载
      //   if (result.data.data.length < this.categroyList[this.active].pageSize) {
      //     this.categroyList[this.active].finished = true;
      //   }
      // },
      this.init();
      // 2000
      // );
    },
    onRefresh() {
      // 页码变成1
      this.categroyList[this.active].pageIndex = 1;
      // 清空数组数据
      this.categroyList[this.active].postList.length = 0;
      // 使用init函数渲染  获取数据
      //把下拉拉刷新，重置为false
      this.categroyList[this.active].isLoading = false;
      this.init();
      console.log(this.categroyList[this.active].postList);
      // 触发可以上拉加载，不显示数据已已经加载完毕
      this.categroyList[this.active].finished = false;
    },
  },
  async mounted() {
    //先获取id
    if ((JSON.parse(window.localStorage.getItem("toutiao_user")) || {}).id) {
      this.id = (
        JSON.parse(window.localStorage.getItem("toutiao_user")) || {}
      ).id;
    }
    // 判断栏目列表是否有再本地存储
    if (window.localStorage.getItem("toutiao_cateList")) {
      let result = JSON.parse(window.localStorage.getItem("toutiao_cateList"));
      // 加上关注，头条，参数
      // 判定有无token
      if (window.localStorage.getItem("toutiao_token")) {
        result.unshift(
          { id: 0, is_top: 1, name: "关注" },
          { id: 999, is_top: 1, name: "头条" }
        );
        this.categroyList = result;
      } else {
        result.unshift({ id: 0, is_top: 1, name: "关注" });
        this.categroyList = result;
      }
    } else {
      let res = await categroyList();
      this.categroyList = res.data.data;
    }
    this.categroyList = this.categroyList.map((item) => {
      return {
        ...item,
        pageIndex: 1,
        pageSize: 5,
        postList: [],
        loading: false, //  存到数组，不存data  是否处于加载状态，加载过程中不触发load事件
        finished: false, //  存到数组，不存data  是否已加载完成，加载完成后不再触发load事件
        isLoading: false,
      };
    });
    this.init();
    // // if (JSON.parse(window.localStorage.getItem("toutiao")).data.user.id) {
    // // this.id = JSON.parse(window.localStorage.getItem("toutiao")).data.user.id;
    // // console.log(this.id);
    // // 调用封装的请求分类
    // let res = await categroyList();
    // // console.log(res.data.data);
    // // 把获取的请求数据给到this.categroyList
    // this.categroyList = res.data.data;
    // // 我们需要改造数据为了
    // this.categroyList = this.categroyList.map((item) => {
    //   return { ...item, pageIndex: 1, pageSize: 5, postList: [] };
    // });
    // // console.log(this.categroyList);
    // // console.log(this.active);
    // // 数据处理之后，我们可以发送请求，获取栏目数据
    // // 例子：  localhost:3000/post?pageIndex=1&pageSize=2&category=8
    // let result = await getpostlist({
    //   category: this.categroyList[this.active].id,
    //   pageIndex: this.categroyList[this.active].pageIndex,
    //   pageSize: this.categroyList[this.active].pageSize,
    // });
    // // console.log(result);
    // // 把得到的列表数据加入到this.categroyList.postList里面
    // this.categroyList[this.active].postList = result.data.data;
    // // console.log(this.categroyList);
    //点击加号，跳转到栏目分类列表，但是伪类元素并不能选择元素绑定事件，在这里我们可以使用事件冒泡,这里我们用到原生js解决，在mother绑定一个时间
    document.querySelector(".van-sticky").onclick = (e) => {
      console.log(e.target.className);
      if (e.target.className === "van-sticky") {
        this.$router.push({ name: "categoryMannager" });
      }
    };
  },
};
</script>

<style lang="less" scoped>
.index {
  /deep/.van-sticky {
    padding-right: 40px;
    &::after {
      content: "+";
      width: 40px;
      height: 44px;
      position: absolute;
      right: 0;
      top: 0;
      font-size: 30px;
      color: #333;
      text-align: center;
      background-color: #fff;
      line-height: 38px;
    }
  }
  // height: 3000px;
  .header {
    height: 40px;
    display: flex;
    justify-content: space-between;
    background-color: #f00;
    align-items: center;
    color: #fff;
  }
  .search {
    flex: 1;
    height: 30px;
    background-color: rgba(255, 255, 255, 0.4);
    border-radius: 15px;
    text-align: center;
    line-height: 30px;
    .van-icon {
      font-size: 16px;
    }
  }
  .van-icon {
    font-size: 24px;
    padding: 0 10px;
  }
  .iconfont {
    font-size: 50px;
    padding: 0 10px;
  }
}
</style>